# -*- coding: utf-8 -*-
import web,errconst,json,datetime,chaosdb,event

class P2pFM:
    def POST(self):
        input = web.input()
        if(hasattr(input, "op") and hasattr(input, "id")):
            op = input.op
            if(op=="open"):
                p2psite = chaosdb.getP2pSite(int(input.id))
                if(p2psite==None):
                    createP2pSite(int(input.id))
                else:
                    reportSiteOpen(int(input.id),datetime.datetime.now())
            elif(op=="closeSite"):
                reportSiteClose(int(input.id))
            elif(op=="addSite" and hasattr(input, "siteid")):
                addSite(int(input.id),int(input.siteid))
            elif(op=="removesite" and hasattr(input, "siteid")):
                removeSite(int(input.id), int(input.siteid))
        else:
            errrst = {"errcode":errconst.P2PFM_WITHOUT_USERID_OR_OPCODE,
                      "errmsg":"","content":""}
            return json.dumps(errrst); 
    
    def GET(self):
        pass
    

def reportSiteOpen(siteOwnerid,opentime):
    chaosdb.updateP2pSiteOpen(siteOwnerid, opentime)
    notifyActivitedListeners(siteOwnerid)
    
def createP2pSite(siteOwnerid):
    dbUser = chaosdb.getDBUser(siteOwnerid)
    if(dbUser!=None):
        chaosdb.createP2pSite(siteOwnerid, dbUser.name+' MHz')
        notifyAllOnlineChaosUser(siteOwnerid,dbUser.name+' MHz')
    
def reportSiteClose(siteid):
    pass

def notifyAllOnlineChaosUser(siteOwnerid,siteName):
    rst =  chaosdb.db.select('user',where='isactivate=1');
    for user in rst:
        now = datetime.datetime.now()
        if((now-user.activietime).days<7):
            event.addEvent(user.uid,event.TYPE_SITEOPEN_NOTIFY_LISTENER,
                        "[type=radio,id=%d,display=%s]开播了"%(siteOwnerid,siteName));

def notifyActivitedListeners(siteOwnerid):
    site = chaosdb.getP2pSite(siteOwnerid)
    if(site!=None and site.listeners!=None):
            listeners=site.listeners.split(",")
            if(len(listeners)>0):
                for useridStr in listeners:
                    user = chaosdb.getDBUser(int(useridStr))
                    if(user!=None and user.isactivate==1):
                        now = datetime.datetime.now()
                        if((now-user.activietime).seconds<60):
                            event.addEvent(int(useridStr),event.TYPE_SITEOPEN_NOTIFY_LISTENER,
                               "[type=radio,id=%d,display=%s]开播了"%(siteOwnerid,site.name));

def loveBroadcastTrack(listener,siteid,trackid):
    pass

def waitSiteOpen(listener,siteid):
    pass    

def addSite(listenerid,siteownerid):
    site = chaosdb.getP2pSite(siteownerid)
    if(site!=None):
        if(site.listeners!=None):
            listeners = site.listeners.split(',')
        else:
            listeners = []
        if((str(listenerid) in listeners)==False):
            listeners.append(str(listenerid))
            chaosdb.updateSiteListeners(siteownerid, listeners)
            
def removeSite(listernerid,siteownerid):
    site = chaosdb.getP2pSite(siteownerid)
    if(site!=None and site.listeners!=None):
        listeners = site.listeners.split(',')
        newlisterners = []
        for listenrIdStr in listeners:
            if(int(listenrIdStr)!=listenrIdStr):
                newlisterners.append(listenrIdStr)
        if(len(newlisterners)<len(listeners)):
            chaosdb.updateSiteListeners(siteownerid, newlisterners)
